package com.yylending.las.lending.quota.credit;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import android.webkit.JavascriptInterface;

import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yylending.las.Constants;
import com.yylending.las.R;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.utils.StorageUtils;

/**
 * Created by laixj on 2017/6/22.
 * Copyright ©2016 www.yylending.com. All Rights Reserved.
 */
public class AuthWebViewActivity extends BaseActivity {

	private final static String TAG = "AuthWebViewActivity";

	private final static String ARG_VERIFY_INFO = "arg_verify_info";
	@BindView(R.id.auth_webView)
	WebView mAuthWebView;
	@BindView(R.id.back_iv)
	ImageView mBackIv;
	@BindView(R.id.auth_webView_loading)
	TextView mAuthWebViewLoading;

	private CreditModel.VerifyInfo mVerifyInfo;

	private Bitmap mAuthCodeBitmap;
	private String mAuthCode = "";

	public static void startForResult(Fragment aty, CreditModel.VerifyInfo verifyInfo, int requestCode) {
		Intent i = new Intent(aty.getActivity(), AuthWebViewActivity.class);
		i.putExtra(ARG_VERIFY_INFO, verifyInfo);
		aty.startActivityForResult(i, requestCode);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {

	}

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_auth_webview);
		ButterKnife.bind(this);
		mVerifyInfo = (CreditModel.VerifyInfo) getIntent().getSerializableExtra(ARG_VERIFY_INFO);
		setTitle(R.string.credit_authority);
		setTopBarVisible(false);
		//启用支持javascript
		WebSettings settings = mAuthWebView.getSettings();
		settings.setJavaScriptEnabled(true);
		mAuthWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setSupportMultipleWindows(true);
		if(mAuthWebView.getX5WebViewExtension() != null){
			CLog.i(TAG, "x5 内核");
		}else{
			CLog.i(TAG, "系统 内核");
		}
		mAuthWebView.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				CLog.i(TAG, "加载url="+url);
				if (url.contains(Constants.AUTH_MERCHANT_ADDRESS)) {
					//跳转到征信认证码提交页
					mAuthWebViewLoading.setVisibility(View.VISIBLE);
					Intent intent = new Intent();
					intent.putExtra(Constants.BANK_AUTH_CODE, mAuthCode);
					setResult(RESULT_OK, intent);
					finish();
				}else if(url.contains("mobile/verify/callback.action?transNumber=")){
					view.loadUrl("javascript:window.local_obj.showSource(" +
							"document.getElementsByClassName('money')[0].innerHTML);");
					int shotHeight = (int)(getResources().getDisplayMetrics().density * 110);
					mAuthCodeBitmap = activityShot(AuthWebViewActivity.this, shotHeight);
					StorageUtils.saveToSD(mAuthCodeBitmap);
				}
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
			}
		});
		mAuthWebView.setWebChromeClient(new WebChromeClient(){

			@Override
			public void onProgressChanged(WebView webView, int progress) {
				super.onProgressChanged(webView, progress);
				if(progress == 100 && mBackIv.getVisibility() == View.GONE){
					mBackIv.setVisibility(View.VISIBLE);
				}
			}
		});

		String dataContent = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
				"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
				"    <head>\n" +
				"        <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" +
				"        <title>\n" +
				"        </title>\n" +
				"    </head>\n" +
				"    <body>\n" +
				"        <form id=\"sform\" action='" + mVerifyInfo.authUrl + "' method=\"post\">\n" +
				"            <input type=\"hidden\" name=\"charset\" id=\"charset\" value='" + mVerifyInfo.charset + "'/>\n" +
				"            <input type=\"hidden\" name=\"serialnumber\" id=\"serialnumber\" value='" + mVerifyInfo.serialNumber + "'/>\n" +
				"            <input type=\"hidden\" name=\"signmethod\" id=\"signmethod\" value='" + mVerifyInfo.signMethod + "'/>\n" +
				"            <input type=\"hidden\" name=\"encrypmethod\" id=\"encrypmethod\" value='" + mVerifyInfo.encrypMethod + "'/>\n" +
				"            <input type=\"hidden\" name=\"signmessage\" id=\"signmessage\"\n" +
				"                   value='" + mVerifyInfo.signMessage + "'/>\n" +
				"            <input type=\"hidden\" name=\"encrypmessage\" id=\"encrypmessage\"\n" +
				"                   value='" + mVerifyInfo.encrypMessage + "'/>\n" +
				"            <input type=\"hidden\" name=\"version\" id=\"version\" value='" + mVerifyInfo.version + "'/>\n" +
				"            <input type=\"hidden\" name=\"certorgcode\" id=\"certorgcode\" value='" + mVerifyInfo.certOrgCode + "'/>\n" +
				"        </form>\n" +
				"    </body>\n" +
				"    <script type=\"text/javascript\">document.all.sform.submit();</script>\n" +
				"\t</body>\n" +
				"</html>";
		CLog.i(TAG, "征信授权报文=" + dataContent);
		mAuthWebView.loadDataWithBaseURL(null, dataContent, "text/html", "utf-8", null);
	}

	final class InJavaScriptLocalObj {
		@JavascriptInterface
		public void showSource(String html) {
			if(!TextUtils.isEmpty(html) && !"undefined".equals(html)){
				mAuthCode = html;
			}
		}
	}

	/**
	 * Activity screenCap * * @param activity * @return
	 */
	public Bitmap activityShot(Activity activity, int shotHeight) {
		/*获取windows中最顶层的view*/
		View view = activity.getWindow().getDecorView();
		//允许当前窗口保存缓存信息
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		//获取状态栏高度
		Rect rect = new Rect();
		view.getWindowVisibleDisplayFrame(rect);
		int statusBarHeight = rect.top;
		WindowManager windowManager = activity.getWindowManager();
		//获取屏幕宽和高
		DisplayMetrics outMetrics = new DisplayMetrics();
		windowManager.getDefaultDisplay().getMetrics(outMetrics);
		int width = outMetrics.widthPixels;
		float density = outMetrics.density;
		int titleHeight = (int)(44 * density);
		//去掉状态栏
		Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, statusBarHeight + titleHeight, width, shotHeight);
		//销毁缓存信息
		view.destroyDrawingCache();
		view.setDrawingCacheEnabled(false);
		return bitmap;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@OnClick(R.id.back_iv)
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.back_iv:
				finish();
				break;
		}
	}
}
